#include "nemu.h"

uint32_t page_translate(vaddr_t va) {
  // pa = (pg_table[va >> 10] & ~0x3ff) | (va & 0x3ff);
  uint32_t paddr = va;
  if(reg_satp & 0x80000000) { // base diretory is valid
    // get the pte
    // printf("start Translation satp =%x\n",reg_satp);
    uint32_t pte_a = (reg_satp << 12) + ((va >> 22) << 2);//(va >> 22);
    // printf("page table address %x\n",pte_a);
    uint32_t pte = paddr_read(pte_a, 4);
    
    if(!(pte & 0x01)) 
      Assert(0,"PTE VALID ERRO valud is %x va is %x",pte,va);
    // if(!(pte & 0x01)) 
    //   Assert(0,"PTE VALID ERRO");
    // printf("pte value is %x\n",pte);
    //get phisical address
    pte = ((pte >> 10) << 12) + (((va << 10) >> 22) << 2);
    // printf("pte addr is %x\n",pte);
    pte = paddr_read(pte, 4);
    if(!(pte & 0x01)) 
      Assert(0,"PTE ADDR VALID ERRO valud is %x",pte);
    paddr = ((pte >> 10) << 12) + (va & 0x0fff);
    // printf("phisical addr is %x\n",paddr);
  }
  return paddr;
}


uint32_t isa_vaddr_read(vaddr_t addr, int len) {
  paddr_t paddr = page_translate(addr);
  return paddr_read(paddr, len);
}

void isa_vaddr_write(vaddr_t addr, uint32_t data, int len) {
  paddr_write(addr, data, len);
}
